<template>
  <div class="examlist_container">
    <div class="title">
      <h2> 法治思维 快乐学法</h2>
    </div>
    <div class="typeSelect">
      <h3>
        {{examInfo.theme}}
      </h3>
    </div>
    <div class="timer">
      <h3>
        考试倒计时 :{{countDownValue}}
      </h3>
    </div>

    <div class="examlist">
      <div class="examInfo">
        <h5>
          【第{{position}}题】 共{{ allQuestionCount }}题
        </h5>
        <p class="question_title">
          <span class="types">【{{currExamTypeStr}}】</span> {{ examContent }}
        </p>
        <div class="questionArea">

          <ul v-if="typeCode == 4 && examList.length > 0">
            <p class="fill-title">请在下方横线处填写答案：</p>
            <van-field label="文本" v-model="updateValues" autosize clearable placeholder="请输入内容" style="-webkit-user-select:text !important" @input="updateValue()" />
          </ul>

          <ul v-else>
            <li :class="item.isSelect?'answer':'answer-default'" v-for="(item,index) in answers" :key="item.id" @click="itemClick(item,index)">
              {{item.content}}
            </li>
          </ul>

        </div>

      </div>

    </div>
    <div class="hr" style="height:100px"></div>
    <div class="step">
      <van-button round type="info" @click="toIndex()">返回</van-button>
      <van-button round type="info" @click="startNextQuestion()">下一题</van-button>
    </div>
  </div>
</template>
<style scoped>
</style>
<script>
import path from '@/network'
import { Toast } from 'vant';
export default {
  name: 'App',

  data () {
    return {
      timer: "", //定时器名字
      countDownNum: 0, //倒计时初始值
      countDownValue: "00:00",

      /// 重新定义变量
      allQuestionCount: 0, // 一共有多少道考试题（所有的类型集合相加）
      currentPos: 0, //当前题型正在作答的集合中的位置
      position: 0, //答题进度 （在所有考题中的进度）
      examList: [], // 不断接收考题的集合 对应多种集合数据 当前类型集合完毕 继续赋值给下一个类型的考题集合
      // 0"判断题" ，1 "单选题"，2"多选题" 3" 不定项选择题" 4"填空题"
      trueorfalseList: [],
      singleList: [],
      multList: [],
      unsurenessList: [],
      completionList: [],

      examInfo: null,//考试详情

      typeCode: 0, //当前考题类型code，
      currExamTypeStr: "", //当前考题文字描述
      examItem: null, //当前正在进行的考题itme
      examContent: "", //问题
      answers: [], //答案
      updateValues: '',
      currentAnswerRecord: [], //存储已经作答的问题集合

      examResultInfo: {
        check_point: 0,
        single_point: 0,
        multiple_point: 0,
        unsureness_point: 0,
        completion_point: 0,
        total_point: 0
      },

    };
  },

  created () {
  },
  beforeDestroy () {
  },

  mounted () {
    this.initData();
    this.typeCode = 0;
    this.setCurrentExamList();
    this.countDown();



  },
  destroyed: function () {
    clearInterval(this.timer);
  },
  methods: {
    //初始化数据
    initData: function () {
      try {
        // 01"判断题" ，1 "单选题"，2"多选题" 3" 不定项选择题" 4"填空题"
        this.trueorfalseList =
          JSON.parse(sessionStorage.getItem("checkQuestions")) ?? [];
        this.singleList =
          JSON.parse(sessionStorage.getItem("singleQuestions")) ?? [];
        this.multList =
          JSON.parse(sessionStorage.getItem("multipleQuestions")) ?? [];
        this.unsurenessList =
          JSON.parse(sessionStorage.getItem("unsurenessQuestions")) ?? [];
        this.completionList =
          JSON.parse(sessionStorage.getItem("completionQuestions")) ?? [];
        this.examInfo =
          JSON.parse(sessionStorage.getItem("examInfo")) ?? [];
        //计算总题数
        this.allQuestionCount =
          this.trueorfalseList.length +
          this.singleList.length +
          this.multList.length +
          this.unsurenessList.length +
          this.completionList.length;
        // console.log("allQuestionCount ==> " + this.allQuestionCount);
      } catch (error) {
        // console.log("初始化题库失败：" + error);
      }
    },
    //填空题输入事件
    updateValue: function () {
      console.log('updateValues', this.updateValues)
      this.examItem.inputAnswer = this.updateValues
    },

    countDown: function () {
      var that = this;
      let value = JSON.parse(sessionStorage.getItem("examInfo"));
      if (value) {
        that.countDownNum = value.duration * 60;
      }
      let second = that.countDownNum; //获取倒计时初始值
      this.timer = setInterval(function () {
        // console.log("second==", second)
        if (second == 600) {
          // that.$message({
          //   showClose: true,
          //   message: "考试时间还剩10分钟，请尽快答题",
          // });

          Toast.fail({
            message: '考试时间还剩10分钟，请尽快答题!',
            forbidClick: true,
          });
          second--;
          that.countDownNum = second;
        } else if (second == 0) {
          // this.examStop()
          clearInterval(this.timer);
        } else {
          second--;
          let m = Math.floor(second / 60);
          let s = second % 60;
          m += "";
          s += "";
          m = m.length == 1 ? "0" + m : m;
          s = s.length == 1 ? "0" + s : s;
          (that.countDownNum = second), (that.countDownValue = m + ":" + s);
        }
      }, 1000);
    },

    //设置当前题库集合
    setCurrentExamList: function () {
      try {
        // console.log("===> " + this.typeCode);
        switch (this.typeCode) {
          case 0:
            this.examList = this.trueorfalseList;
            if (this.examList.length > 0) {
              this.currExamTypeStr = "判断题";
            }
            break;
          case 1:
            this.examList = this.singleList;
            if (this.examList.length > 0) {
              this.currExamTypeStr = "单选题";
            }
            break;
          case 2:
            this.examList = this.multList;
            if (this.examList.length > 0) {
              this.currExamTypeStr = "多选题";
            }
            break;
          case 3:
            this.examList = this.unsurenessList;
            if (this.examList.length > 0) {
              this.currExamTypeStr = "不定项选择题";
            }
            break;
          case 4:
            this.examList = this.completionList;
            if (this.examList.length > 0) {
              this.currExamTypeStr = "填空题";
            }

            break;
        }
      } catch (e) {
        console.log(">> 无法获取当前类型的题库 <<" + e);
      }
      if (this.examList && this.examList.length > 0) {
        this.position++;
        this.updatePageData(this.currentPos);
      } else {
        if (this.typeCode < 4) {
          this.typeCode++;
          this.currentPos = 0;
          this.setCurrentExamList();
        }
      }
    },

    //本轮 答题结束 打开结果
    computScore: function () {
      let trueorfalseRecord = JSON.parse(sessionStorage.getItem("checkRecord"));
      let singleRecord = JSON.parse(sessionStorage.getItem("singleRecord"));
      let multRecord = JSON.parse(sessionStorage.getItem("multipleRecord"));
      let unsureRecord = JSON.parse(sessionStorage.getItem("unsurenessRecord"));
      let completionRecord = JSON.parse(sessionStorage.getItem("completionRecord"));
      let examPaper = JSON.parse(sessionStorage.getItem("examPaper"));
      // 判断题
      if (trueorfalseRecord && trueorfalseRecord.length > 0) {
        var checkmap = {};
        trueorfalseRecord.forEach((item) => {
          item.answers.forEach((innerItem) => {
            if (innerItem.correct == 1) {
              var correctId = innerItem.id;
              item.selectItems.forEach((id) => {
                if (correctId == id) {
                  // 加分
                  this.examResultInfo.check_point += examPaper.checkPoint;
                }
              })
            }
          })
          checkmap[item.id] = item.selectItems;
        })
        this.examResultInfo.checkRecord = checkmap;
        // console.log('checkRecord===>', this.examResultInfo.checkRecord)
      }

      // 单选题 
      if (singleRecord && singleRecord.length > 0) {
        var singlemap = {};
        singleRecord.forEach((item) => {
          // console.log("单选题 item ==" + item.selectItems);
          item.answers.forEach((innerItem) => {
            if (innerItem.correct == 1) {
              var correctId = innerItem.id;
              if (item.selectItems.indexOf(correctId) != -1) {
                // 加分
                this.examResultInfo.single_point += examPaper.singlePoint;
              }
            }
          })
          singlemap[item.id] = item.selectItems;
        })
        this.examResultInfo.singleRecord = singlemap;
        console.log('singleRecord===>', this.examResultInfo.singleRecord)
      }
      //多选和不定向
      if (multRecord && multRecord.length > 0) {
        var multmap = {};
        multRecord.forEach((item) => {
          multmap[item.id] = item.selectItems;
          if (item.selectItems.length != item.correctCount) {
            // 回答错误 不计分 继续下一个循环
            return;
          }
          var isRight = true;
          item.answers.forEach((innerItem) => {

            if (innerItem.correct == 1) {
              var correctId = innerItem.id;
              if (item.selectItems.indexOf(correctId) == -1) {
                //一旦发现有一个正确答案 用户没有选择 立即终止循环 不进行加分
                isRight = false;
                return;
              }
            }
          })

          if (isRight) {
            // 加分
            this.examResultInfo.multiple_point += examPaper.multiplePoint;
          }

        })
        this.examResultInfo.multipleRecord = multmap;
        console.log('multRecord===>', this.examResultInfo.multipleRecord)
      }
      var unmap = {}
      if (unsureRecord && unsureRecord.length > 0) {
        unsureRecord.forEach((item) => {
          unmap[item.id] = item.selectItems;
          if (item.selectItems.length != item.correctCount) {
            // 回答错误 不计分 继续下一个循环
            return;
          }
          var isRight = true;
          item.answers.forEach((innerItem) => {
            if (innerItem.correct == 1) {
              var correctId = innerItem.id;
              if (item.selectItems.indexOf(correctId) == -1) {
                //一旦发现有一个正确答案 用户没有选择 立即终止循环 不进行加分
                isRight = false;
                return;
              }
            }
          })

          if (isRight) {
            // 加分
            this.examResultInfo.unsureness_point += examPaper.unsurenessPoint;
          }

        })
      }
      this.examResultInfo.unsureRecord = unmap;
      //填空题

      var commap = {}
      if (completionRecord && completionRecord.length > 0) {
        completionRecord.forEach((item) => {
          // console.log('completionRecord=item===>', item)
          item.answers.forEach((innerItem) => {
            if (innerItem.correct_content == item.inputAnswer) {
              //答对加分
              this.examResultInfo.completion_point += examPaper.completion_point;
            }

          })

          commap[item.id] = [item.inputAnswer];
          // console.log('commap====>', commap)
        })
      }
      this.examResultInfo.completionRecord = commap;

      // 总分
      this.examResultInfo.total_point = parseInt(this.examResultInfo.check_point) + parseInt(this.examResultInfo.single_point) + parseInt(this.examResultInfo.multiple_point) + parseInt(this.examResultInfo.unsureness_point) + parseInt(this.examResultInfo.completion_point)

      sessionStorage.setItem("examResultInfo", JSON.stringify(this.examResultInfo))
      sessionStorage.setItem("examResultInfo", JSON.stringify(this.examResultInfo))
      this.sumbitRecord()

    },

    //单选 多选 判断题的点击事件 + 不定项选择题

    //时间到 考试结束
    examStop: function () {
      //本地保存答题记录
      switch (Number(this.typeCode)) {
        case 0:
          sessionStorage.setItem(
            "checkRecord",
            JSON.stringify(this.currentAnswerRecord)
          );
          // console.log("unsurenessRecord", currentAnswerRecord)
          break;
        case 1:
          sessionStorage.setItem(
            "singleRecord",
            JSON.stringify(this.currentAnswerRecord)
          );
          // console.log("singleRecord", currentAnswerRecord)
          break;
        case 2:
          sessionStorage.setItem(
            "multipleRecord",
            JSON.stringify(this.currentAnswerRecord)
          );
          // console.log("multipleRecord", currentAnswerRecord)
          break;
        case 3:
          sessionStorage.setItem("unsurenessRecord", JSON.stringify(this.currentAnswerRecord));
          // console.log("checkRecord", currentAnswerRecord)
          break;
        case 4:
          sessionStorage.setItem(
            "completionRecord",
            JSON.stringify(this.currentAnswerRecord)
          );
          console.log("completionRecord", this.currentAnswerRecord)
          break;
      }

      this.computScore()
    },


    startNextQuestion: function () {
      if (this.typeCode == "4") {
        this.updateValues = ''
      }
      if (this.examItem.selectItems.length > 0 || this.examItem.inputAnswer != "") {
        if (this.typeCode == "2" && this.examItem.selectItems.length < 2) {
          // this.$message({
          //   message: "多选题，请至少选择两个答案",
          //   showClose: true,
          // });

          Toast.fail({
            message: '多选题，请至少选择两个答案!',
            forbidClick: true,
          });
          return;
        }

        if (this.currentPos <= this.examList.length - 1) {
          this.currentAnswerRecord.push(this.examItem);
        }
        if (this.currentPos < this.examList.length - 1) {
          this.currentPos++;
          this.updatePageData(this.currentPos);
          this.position++;
        } else {
          //本地保存答题记录
          switch (Number(this.typeCode)) {
            case 0:
              sessionStorage.setItem(
                "checkRecord",
                JSON.stringify(this.currentAnswerRecord)
              );
              // console.log("unsurenessRecord", currentAnswerRecord)
              break;
            case 1:
              sessionStorage.setItem(
                "singleRecord",
                JSON.stringify(this.currentAnswerRecord)
              );
              // console.log("singleRecord", currentAnswerRecord)
              break;
            case 2:
              sessionStorage.setItem(
                "multipleRecord",
                JSON.stringify(this.currentAnswerRecord)
              );
              // console.log("multipleRecord", currentAnswerRecord)
              break;
            case 3:
              sessionStorage.setItem("unsurenessRecord", JSON.stringify(this.currentAnswerRecord));
              // console.log("checkRecord", currentAnswerRecord)
              break;
            case 4:
              sessionStorage.setItem(
                "completionRecord",
                JSON.stringify(this.currentAnswerRecord)
              );
              console.log("completionRecord", this.currentAnswerRecord)
              break;
          }


          this.typeCode++;
          if (this.typeCode < 5) {
            this.currentPos = 0;
            this.currentAnswerRecord = [];
            this.setCurrentExamList();

            // console.log("本地保存答题记录完成");
          }

          if (this.allQuestionCount == this.position) {
            // 最后一题也做完了 这里提交结果
            // console.log("----向服务器提交结果--------");
            this.computScore();
            clearInterval(this.timer);
          }
        }
      } else {
        // this.$message({
        //   message: "请先作答",
        // });
        Toast.fail({
          message: '请先作答!',
          forbidClick: true,
        });
        return;
      }
    },

    //更新页面数据
    updatePageData (index) {
      var that = this;
      that.examItem = {
        id: that.examList[index].id,
        correctCount: that.examList[index].correctCount,
        content: that.examList[index].content,
        answers: that.examList[index].answers,
        selectItems: [],
        inputAnswer: "",
      };
      for (var i = 0; i < that.examItem.answers.length; i++) {
        that.examItem.answers[i].isSelect = false;
      }
      this.examContent = that.examItem.content;
      this.answers = this.examItem.answers;

      //todo 这里如果是连续的填空题肯能会带入上一题的输入内容 清空即可

    },

    itemClick: function (item, positon) {
      var pos = positon;
      var answerId = item.id;
      let index = this.examItem.selectItems.indexOf(answerId);
      switch (Number(this.typeCode)) {
        case 0:
          //判断
          if (index == -1) {
            this.examItem.selectItems = [];
            this.examItem.selectItems.push(answerId);
            this.examItem.answers[pos].isSelect = true;
            for (let i = 0; i < this.examItem.answers.length; i++) {
              if (pos != i) {
                this.examItem.answers[i].isSelect = false;
              }
            }
          } else {
            this.examItem.answers[pos].isSelect = false;
            this.examItem.selectItems = [];
          }

          break;
        case 1:
          //单选
          // console.log("单选")
          if (index == -1) {
            this.examItem.selectItems = [];
            this.examItem.selectItems.push(answerId);
            this.examItem.answers[pos].isSelect = true;
            this.examItem.answers.forEach((value, index) => {
              if (pos != index) {
                this.examItem.answers[index].isSelect = false;
              }
            });
          } else {
            this.examItem.answers[pos].isSelect = false;
            this.examItem.selectItems = [];
          }
          break;
        case 2:
          //多选
          // console.log("多选")
          if (index == -1) {
            this.examItem.selectItems.push(answerId);
            this.examItem.answers[pos].isSelect = true;
          } else {
            this.examItem.answers[pos].isSelect = false;
            this.examItem.selectItems.splice(index, 1);
          }
          break;
        case 3:
          //不定项
          // console.log("不定项")
          if (index == -1) {
            this.examItem.selectItems.push(answerId);
            this.examItem.answers[pos].isSelect = true;
          } else {
            this.examItem.answers[pos].isSelect = false;
            this.examItem.selectItems.splice(index, 1);
          }
          break;
      }
      // console.log("examItem", examItem)
      this.answers = this.examItem.answers;
      // 强制更新页面 参考https://www.cnblogs.com/Super-scarlett/p/11132034.html
      this.$forceUpdate();
    },


    //提交成绩
    sumbitRecord () {
      path.addRecord({
        examId: this.$route.query.id,
        single_point: this.examResultInfo.single_point,
        multiple_point: this.examResultInfo.multiple_point,
        check_point: this.examResultInfo.check_point,
        completion_point: this.examResultInfo.completion_point,
        unsureness_point: this.examResultInfo.unsureness_point,
        unsurenessRecord: this.examResultInfo.unsureRecord,
        singleRecord: this.examResultInfo.singleRecord,
        multipleRecord: this.examResultInfo.multipleRecord,
        checkRecord: this.examResultInfo.checkRecord,
        completionRecord: this.examResultInfo.completionRecord,
      }).then(res => {
        if (res.success == 0) {
          // this.$message({
          //   message: "成绩提交成功",
          // });
          Toast.success({
            message: '成绩提交成功!',
            forbidClick: true,
          });
          this.$router.push({ name: "examResult", query: { id: this.$route.query.id } });
        }
      })
    },


    toIndex: function () {
      this.$router.push({ name: "examList" });
    },

  },
};


</script>